//
//  CascadeListView.m
//  etionRichText
//
//  Created by wangjian on 11/15/13.
//
//

#import "CascadeListView.h"

#define MARGIN 15
#define CELL_TITLE_H 20

@implementation CCascadeListCell
{
    UILabel *_titleLable;
    UIImageView *_operationImageView;
}

- (UIImage *)imageForType:(ECascadeSelectorCellDataType)type selected:(BOOL)selected
{
    NSString *imageName = nil;
    switch (type)
    {
        case ECascadeSelectorCellDataTypeSet:
            imageName = @"gtv_cell_disclosure";
            break;
        case ECascadeSelectorCellDataTypeSingleSelector:
            imageName = selected ? @"list_selected" : @"";
            break;
        case ECascadeSelectorCellDataTypeMultiSelector:
            imageName = selected ? @"list_selected" : @"";
            break;
        default:
            break;
    }
    
    return [UIImage imageNamed:imageName];
}

- (void)updateWithData:(CCascadeSelectorCellData *)data animated:(BOOL)animated
{
    if (_titleLable == nil)
    {
        _titleLable = [[[UILabel alloc] initWithFrame:CGRectMake(MARGIN, (self.height-CELL_TITLE_H)/2, self.width-2*MARGIN, CELL_TITLE_H)] autorelease];
        _titleLable.backgroundColor = [UIColor clearColor];
        _titleLable.font = [UIFont systemFontOfSize:14];
        [self addSubview:_titleLable];
    }
    _titleLable.text = data.title;
    
    [self updateForType:data.type selected:data.selected animated:animated];
}

- (void)updateForType:(ECascadeSelectorCellDataType)type selected:(BOOL)selected animated:(BOOL)animated
{
    UIImage *image = [self imageForType:type selected:selected];
    if (image == nil)
    {
        if (_operationImageView != nil)
        {
            _titleLable.frame = CGRectMake(MARGIN, (self.height-CELL_TITLE_H)/2, self.width-2*MARGIN, CELL_TITLE_H);
            if (animated)
            {
                [UIView animateWithDuration:.25 animations:^{
                    _operationImageView.alpha = 0.0;
                    _operationImageView.frame = CGRectMake(_operationImageView.centerX, _operationImageView.centerY, 1, 1);
                } completion:^(BOOL finished) {
                    [_operationImageView removeFromSuperview];
                    _operationImageView = nil;
                }];
            }
            else
            {
                [_operationImageView removeFromSuperview];
                _operationImageView = nil;
            }
        }
    }
    else
    {
        if (_operationImageView == nil)
        {
            _operationImageView = [[[UIImageView alloc] initWithImage:image] autorelease];
            [self addSubview:_operationImageView];
        }
        else
        {
            _operationImageView.image = image;
        }
        _operationImageView.frame = CGRectMake(self.width-MARGIN-image.size.width, (NSInteger)(self.height-image.size.height)/2, image.size.width, image.size.height);
        _titleLable.frame = CGRectMake(_titleLable.left, _titleLable.top, self.width-3*MARGIN-image.size.width, _titleLable.height);
        if (animated)
        {
            _operationImageView.alpha = 0.0;
            _operationImageView.frame = CGRectMake(_operationImageView.centerX, _operationImageView.centerY, 1, 1);
            [UIView animateWithDuration:.25 animations:^{
                _operationImageView.frame = CGRectMake(self.width-MARGIN-image.size.width, (NSInteger)(self.height-image.size.height)/2, image.size.width, image.size.height);
                _operationImageView.alpha = 1.0;
            }];
        }
    }
}

@end

@interface CCascadeListView() <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) NSArray *items;
@property (nonatomic, retain) NSMutableArray *filterItems;
@property (nonatomic, assign, getter = isFiltering) BOOL filtering;

@end

@implementation CCascadeListView
{
    UITableView *_tableView;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.layer.shadowOpacity = .5;
        _tableView = [[[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain] autorelease];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [self addSubview:_tableView];
    }
    return self;
}

- (void)dealloc
{
    [_items release];
    [_filterItems release];
    [super dealloc];
}

- (void)didMoveToSuperview
{
    [super didMoveToSuperview];
    if (self.superview != nil)
    {
    [_tableView reloadData];
}
}

- (void)setEdgeInsets:(UIEdgeInsets)edgeInsets
{
    CGFloat offsetY = 0;
    if (_tableView.contentOffset.y != -_tableView.contentInset.top)
    {
        offsetY = _tableView.contentOffset.y + _tableView.contentInset.top;
    }
    [_tableView setContentInset:edgeInsets];
    if (offsetY != 0)
    {
        _tableView.contentOffset = CGPointMake(0, -_tableView.contentInset.top+offsetY);
    }
}

- (void)setCellItems:(NSArray *)arItems
{
    self.items = arItems;
}

- (CCascadeListCell *)cellAtIndexPath:(NSIndexPath *)indexPath
{
    return (CCascadeListCell *)[_tableView cellForRowAtIndexPath:indexPath];
}

- (void)filterWithCondition:(NSString *)condition
{
    if (condition.length == 0)
    {
        if (self.isFiltering == YES)
        {
            self.filtering = NO;
            [_tableView reloadData];
        }
    }
    else
    {
        self.filtering = YES;
        if (self.filterItems == nil)
        {
            self.filterItems = [NSMutableArray array];
        }
        else
        {
            [self.filterItems removeAllObjects];
        }
        
        for (CCascadeSelectorCellData *data in self.items)
        {
            if ([data.title rangeOfString:condition].location != NSNotFound)
            {
                [self.filterItems addObject:data];
            }
        }
        
        [_tableView reloadData];
    }
}

- (void)scrollToMakeItemVisible:(CCascadeSelectorCellData *)data animated:(BOOL)animated
{
    NSUInteger index = [self.items indexOfObject:data];
    if (index == NSNotFound)
    {
        return;
    }
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:animated];
}

#pragma mark -

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.filtering == YES ? self.filterItems.count : self.items.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CCascadeListCell *cell = (CCascadeListCell *)[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
    {
        cell = [[[CCascadeListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"] autorelease];
        cell.frame = CGRectMake(0, 0, tableView.width, 40);
    }
    [cell updateWithData:[(self.filtering == YES ? self.filterItems : self.items) objectAtIndex:indexPath.row] animated:NO];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.delegate cascadeListView:self didClickCell:(CCascadeListCell *)[tableView cellForRowAtIndexPath:indexPath] forData:[(self.filtering == YES ? self.filterItems : self.items) objectAtIndex:indexPath.row]];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([self.delegate respondsToSelector:@selector(cascadeListView:didScrollToOffset:)])
    {
        [self.delegate cascadeListView:self didScrollToOffset:CGPointMake(scrollView.contentOffset.x+scrollView.contentInset.left, scrollView.contentOffset.y+scrollView.contentInset.top)];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if ([self.delegate respondsToSelector:@selector(cascadeListView:didEndDragAtOffset:)])
    {
        [self.delegate cascadeListView:self didEndDragAtOffset:CGPointMake(scrollView.contentOffset.x+scrollView.contentInset.left, scrollView.contentOffset.y+scrollView.contentInset.top)];
    }
}

@end

